package com.exercise.ThreadSynchronization.SynchronizedCode;

public class SyncBlockCounter {
    private int count = 0;
    // 使用同步代码块，锁对象是 this
    //也可以使用自定义锁对象
    private final Object lock = new Object();
    public void increment() {
        //synchronized (this) {
        synchronized (lock) { // 使用自定义锁对象
            count++;
            System.out.println("Count: " + count + " by " + Thread.currentThread().getName());
        }
    }
    public int getCount() {
        return count;
    }
    public static void main(String[] args) throws InterruptedException {
        // 创建共享的计数器对象
        SyncBlockCounter counter = new SyncBlockCounter();
        // 定义任务：每个线程调用 1000 次 increment
        Runnable task = () -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        };

        // 创建两个线程
        Thread thread1 = new Thread(task, "Thread-1");
        Thread thread2 = new Thread(task, "Thread-2");

        // 启动线程
        thread1.start();
        thread2.start();

        // 等待线程结束
        thread1.join();
        thread2.join();

        // 输出最终计数
        System.out.println("Final count: " + counter.getCount()); // 预期输出：2000
    }
}
